package com.cenxi.ipdemo1.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Component
public class RedisDistributedLock {
 
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
 
    // 锁的过期时间，单位毫秒
    private static final long LOCK_EXPIRE_TIME = 30000;
 
    // 获取锁的 Lua 脚本
    private static final String LOCK_SCRIPT =
            "if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then " +
                    "redis.call('pexpire', KEYS[1], ARGV[2]); " +
                    "return true; " +
                    "else return false; " +
                    "end";
 
    // 释放锁的 Lua 脚本
    private static final String UNLOCK_SCRIPT =
            "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                    "redis.call('del', KEYS[1]); " +
                    "return true; " +
                    "else return false; " +
                    "end";
 
    // 获取分布式锁
    public boolean lock(String key, String value) {
        List<String> keys = Collections.singletonList(key);
        RedisScript<Boolean> script = new DefaultRedisScript<>(LOCK_SCRIPT, Boolean.class);
        return redisTemplate.execute(script, keys, value, String.valueOf(LOCK_EXPIRE_TIME));
    }
 
    // 释放分布式锁
    public boolean unlock(String key, String value) {
        List<String> keys = Collections.singletonList(key);
        RedisScript<Boolean> script = new DefaultRedisScript<>(UNLOCK_SCRIPT, Boolean.class);
        return redisTemplate.execute(script, keys, value);
    }
}